import sys
import asyncio
import functools

async def func():
    result = await asyncio.sleep(3,result="执行结束")
    print(result)
    #如果没有对loop stop , run_forever 会一直阻塞
    asyncio.get_event_loop().stop()

def main():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    if sys.platform != "win32":
        watcher = asyncio.get_child_watcher()
        watcher.attach_loop(loop)
    try:
        asyncio.ensure_future(func())
        loop.run_forever()
        print("game over")
    finally:
        try:
            loop.run_until_complete(loop.shutdown_asyncgens())
        finally:
            loop.close()


async def worker(times:int):
    result = await asyncio.sleep(times,result=f"{times}执行结束")
    print(result)
    return result

def callback_done(future):
    """
    asyncio.gather 结束后的回调处理函数
    """
    print(future)

    future.get_loop().stop()

def main_gather():

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    if sys.platform != "win32":
        watcher = asyncio.get_child_watcher()
        watcher.attach_loop(loop)
    try:
        future = asyncio.gather(worker(1),worker(2),worker(3))
        future.add_done_callback(callback_done)
        loop.run_forever()
        print("game over")
    finally:
        try:
            loop.run_until_complete(loop.shutdown_asyncgens())
        finally:
            loop.close()



if __name__ == '__main__':
    main_gather()